package com.tongqin.distributed.service;


import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author yuantongqin
 * @date 2018/8/20 下午5:00
 */
public class SocketService {

    public static void main(String[] args) {

        try {
            ServerSocket serverSocket = new ServerSocket(8081);

            //通过无线循环监听客户端连接
            //如果没有客户端接入，将阻塞在accept操作上。
            while(true){

                Socket socket = serverSocket.accept();
                //当有新的客户端接入时，会执行下面的代码
                //然后创建一个新的线程处理这条Socket链路

                new Thread(new ServerHandler(socket)).start();


                InputStream inputStream = socket.getInputStream();


                byte[] bytes= new byte[1024];

                StringBuffer sb = new StringBuffer();
                while (inputStream.read(bytes)!=-1){
                    sb.append(new String(bytes,0,bytes.length));

                }

                System.out.println("客户端发送过来的消息："+sb.toString());
                //此时我们要返回一些消息给客户端
                OutputStream outputStream = socket.getOutputStream();

                outputStream.write("服务端返回给客户端的消息".getBytes());





            }




        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //关闭操作
        }

    }
}
